package main

import (
	"context"
	"flag"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"os"
	"timeTask/internal/config"
	timetaskServer "timeTask/internal/server/timetask"
	"timeTask/internal/svc"
	"timeTask/pb"

	"github.com/robfig/cron/v3"
	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/core/service"
	"github.com/zeromicro/go-zero/zrpc"
	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
)

// var configFile = flag.String("f", "etc/timetask.yaml", "the config file")
var env string

func main() {
	flag.Parse()
	if envEnv := os.Getenv("GO_ENV"); envEnv != "" {
		env = envEnv
	}

	if env == "" {
		env = "dev" // 默认使用开发环境
	}

	var configPath string
	switch env {
	case "dev":
		configPath = "etc/timetask.yaml"
	case "uat":
		configPath = "etc/timetask-uat.yaml"
	case "prd":
		configPath = "etc/timetask-prd.yaml"
	default:
		fmt.Println("Unknown environment:", env)
		return
	}

	fmt.Println("configPat:", configPath)
	var configFile = flag.String("f", configPath, "the config file")
	var c config.Config
	conf.MustLoad(*configFile, &c)
	ctx := svc.NewServiceContext(c)

	s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) {
		pb.RegisterTimeTaskServer(grpcServer, timetaskServer.NewTimeTaskServer(ctx))

		if c.Mode == service.DevMode || c.Mode == service.TestMode {
			reflection.Register(grpcServer)
		}
	})

	cronScheduler := cron.New(cron.WithSeconds()) // 允许使用秒级cron表达式
	// 参数意思 查看 https://www.cnblogs.com/beatle-go/p/17472105.html
	_, err := cronScheduler.AddFunc("0 0 0 * * *", func() {
		CtxBg := context.Background()
		server := timetaskServer.NewTimeTaskServer(ctx)
		params := pb.Emp{}
		_, err := server.TaskMysql(CtxBg, &params)
		if err != nil {
			logx.Errorf("执行任务失败: %v", err)
		}
		logx.Infof("任务正常执行中。。")
	})
	if err != nil {
		logx.Errorf("添加定时任务失败: %v", err)
		return
	}
	cronScheduler.Run()
	defer cronScheduler.Stop()
	defer s.Stop()

	fmt.Printf("Starting rpc server at %s...\n", c.ListenOn)
	s.Start()
}
